提交 4989b7f8 编写于 作者: Q qiang

Merge branch 'dev' into alpha

# Conflicts:
#	packages/vue-cli-plugin-uni/package.json
...@@ -19,12 +19,13 @@ function transform(content) { ...@@ -19,12 +19,13 @@ function transform(content) {
} }
function getIndexCssPath(assetsDir, template) { function getIndexCssPath(assetsDir, template) {
const CopyWebpackPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
const VUE_APP_INDEX_CSS_HASH = process.env.VUE_APP_INDEX_CSS_HASH const VUE_APP_INDEX_CSS_HASH = process.env.VUE_APP_INDEX_CSS_HASH
if (VUE_APP_INDEX_CSS_HASH) { if (VUE_APP_INDEX_CSS_HASH) {
try { try {
const templateContent = fs.readFileSync(getTemplatePath(template)) const templateContent = fs.readFileSync(getTemplatePath(template))
if (/\bVUE_APP_INDEX_CSS_HASH\b/.test(templateContent)) { if (/\bVUE_APP_INDEX_CSS_HASH\b/.test(templateContent)) {
return path.join(assetsDir, `[name].${VUE_APP_INDEX_CSS_HASH}.[ext]`) return path.join(assetsDir, `[name].${VUE_APP_INDEX_CSS_HASH}${CopyWebpackPluginVersion > 5 ? '' : '.'}[ext]`)
} }
} catch (e) {} } catch (e) {}
} }
......
...@@ -6,12 +6,17 @@ const COMPONENTS_DIR_NAME = 'wxcomponents' ...@@ -6,12 +6,17 @@ const COMPONENTS_DIR_NAME = 'wxcomponents'
function getComponentsCopyOption () { function getComponentsCopyOption () {
if (process.env.UNI_OUTPUT_TMP_DIR) { // TODO v3不需要,即将废弃 if (process.env.UNI_OUTPUT_TMP_DIR) { // TODO v3不需要,即将废弃
const componentsDir = path.resolve(process.env.UNI_INPUT_DIR, COMPONENTS_DIR_NAME) const componentsDir = path.resolve(process.env.UNI_INPUT_DIR, COMPONENTS_DIR_NAME)
const CopyWebpackPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
if (fs.existsSync(componentsDir)) { if (fs.existsSync(componentsDir)) {
return { const ignore = ['**/*.vue', '**/*.css']
return Object.assign({
from: componentsDir, from: componentsDir,
to: COMPONENTS_DIR_NAME, to: COMPONENTS_DIR_NAME
ignore: ['**/*.vue', '**/*.css'] }, CopyWebpackPluginVersion > 5 ? {
} globOptions: { ignore }
} : {
ignore
})
} }
} }
} }
......
...@@ -22,6 +22,7 @@ module.exports = { ...@@ -22,6 +22,7 @@ module.exports = {
subPackages: true subPackages: true
}, },
copyWebpackOptions (platformOptions, vueOptions) { copyWebpackOptions (platformOptions, vueOptions) {
const CopyWebpackPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
const copyOptions = [ const copyOptions = [
// 'sitemap.json', // 'sitemap.json',
// 'ext.json', // 'ext.json',
...@@ -31,21 +32,29 @@ module.exports = { ...@@ -31,21 +32,29 @@ module.exports = {
workers && copyOptions.push(workers) workers && copyOptions.push(workers)
const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, COMPONENTS_DIR_NAME) const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, COMPONENTS_DIR_NAME)
const ignore = ['**/*.vue', '**/*.css'] // v3 会自动转换生成vue,css文件,需要过滤
if (fs.existsSync(wxcomponentsDir)) { if (fs.existsSync(wxcomponentsDir)) {
copyOptions.push({ copyOptions.push(Object.assign({
from: wxcomponentsDir, from: wxcomponentsDir,
to: COMPONENTS_DIR_NAME, to: COMPONENTS_DIR_NAME
ignore: ['**/*.vue', '**/*.css'] // v3 会自动转换生成vue,css文件,需要过滤 }, CopyWebpackPluginVersion > 5 ? {
}) globOptions: { ignore }
} : {
ignore
}))
} }
global.uniModules.forEach(module => { global.uniModules.forEach(module => {
const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, 'uni_modules', module, COMPONENTS_DIR_NAME) const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, 'uni_modules', module, COMPONENTS_DIR_NAME)
if (fs.existsSync(wxcomponentsDir)) { if (fs.existsSync(wxcomponentsDir)) {
copyOptions.push({ copyOptions.push(Object.assign({
from: wxcomponentsDir, from: wxcomponentsDir,
to: 'uni_modules/' + module + '/' + COMPONENTS_DIR_NAME, to: 'uni_modules/' + module + '/' + COMPONENTS_DIR_NAME
ignore: ['**/*.vue', '**/*.css'] // v3 会自动转换生成vue,css文件,需要过滤 }, CopyWebpackPluginVersion > 5 ? {
}) globOptions: { ignore }
} : {
ignore
}))
} }
}) })
return copyOptions return copyOptions
......
...@@ -24,12 +24,13 @@ module.exports = { ...@@ -24,12 +24,13 @@ module.exports = {
darkmode: true darkmode: true
}, },
copyWebpackOptions (platformOptions, vueOptions) { copyWebpackOptions (platformOptions, vueOptions) {
const CopyWebpackPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
const copyOptions = [ const copyOptions = [
'theme.json', 'theme.json',
'sitemap.json', 'sitemap.json',
'ext.json', 'ext.json',
'custom-tab-bar', 'custom-tab-bar',
'functional-pages', 'functional-pages',
'project.private.config.json' 'project.private.config.json'
] ]
...@@ -46,25 +47,32 @@ module.exports = { ...@@ -46,25 +47,32 @@ module.exports = {
const manifestConfig = process.UNI_MANIFEST const manifestConfig = process.UNI_MANIFEST
const weixinConfig = manifestConfig['mp-weixin'] || {} const weixinConfig = manifestConfig['mp-weixin'] || {}
const copyWxComponentsOnDemandSwitch = !!weixinConfig.copyWxComponentsOnDemand // 默认值false const copyWxComponentsOnDemandSwitch = !!weixinConfig.copyWxComponentsOnDemand // 默认值false
const ignore = ['**/*.vue', '**/*.css'] // v3 会自动转换生成vue,css文件,需要过滤
if (!copyWxComponentsOnDemandSwitch) { if (!copyWxComponentsOnDemandSwitch) {
const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, COMPONENTS_DIR_NAME) const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, COMPONENTS_DIR_NAME)
if (fs.existsSync(wxcomponentsDir)) { if (fs.existsSync(wxcomponentsDir)) {
copyOptions.push({ copyOptions.push(Object.assign({
from: wxcomponentsDir, from: wxcomponentsDir,
to: COMPONENTS_DIR_NAME, to: COMPONENTS_DIR_NAME
ignore: ['**/*.vue', '**/*.css'] // v3 会自动转换生成vue,css文件,需要过滤 }, CopyWebpackPluginVersion > 5 ? {
}) globOptions: { ignore }
} : {
ignore
}))
} }
} }
global.uniModules.forEach(module => { global.uniModules.forEach(module => {
const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, 'uni_modules', module, COMPONENTS_DIR_NAME) const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, 'uni_modules', module, COMPONENTS_DIR_NAME)
if (fs.existsSync(wxcomponentsDir)) { if (fs.existsSync(wxcomponentsDir)) {
copyOptions.push({ copyOptions.push(Object.assign({
from: wxcomponentsDir, from: wxcomponentsDir,
to: 'uni_modules/' + module + '/' + COMPONENTS_DIR_NAME, to: 'uni_modules/' + module + '/' + COMPONENTS_DIR_NAME
ignore: ['**/*.vue', '**/*.css'] // v3 会自动转换生成vue,css文件,需要过滤 }, CopyWebpackPluginVersion > 5 ? {
}) globOptions: { ignore }
} : {
ignore
}))
} }
}) })
return copyOptions return copyOptions
......
...@@ -2,6 +2,7 @@ const path = require('path') ...@@ -2,6 +2,7 @@ const path = require('path')
const webpack = require('webpack') const webpack = require('webpack')
const CopyPlugin = require('copy-webpack-plugin') const CopyPlugin = require('copy-webpack-plugin')
const CopyPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
const HandlerPlugin = require('@hap-toolkit/packager/lib/plugin/handler-plugin') const HandlerPlugin = require('@hap-toolkit/packager/lib/plugin/handler-plugin')
const ZipPlugin = require('@hap-toolkit/packager/lib/plugin/zip-plugin') const ZipPlugin = require('@hap-toolkit/packager/lib/plugin/zip-plugin')
...@@ -39,6 +40,11 @@ function genPriorities (entryPagePath) { ...@@ -39,6 +40,11 @@ function genPriorities (entryPagePath) {
const uniCloudPath = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/uni-cloud/dist/index.js') const uniCloudPath = require.resolve('@dcloudio/vue-cli-plugin-uni/packages/uni-cloud/dist/index.js')
const patterns = [{
from: path.resolve(__dirname, '../dist/' + dslFilename),
to: 'dsl.js'
}]
module.exports = { module.exports = {
devtool: false, devtool: false,
entry () { entry () {
...@@ -77,10 +83,7 @@ module.exports = { ...@@ -77,10 +83,7 @@ module.exports = {
new webpack.ProvidePlugin({ new webpack.ProvidePlugin({
uniCloud: [uniCloudPath, 'default'] uniCloud: [uniCloudPath, 'default']
}), }),
new CopyPlugin([{ new CopyPlugin(CopyPluginVersion > 5 ? { patterns } : patterns),
from: path.resolve(__dirname, '../dist/' + dslFilename),
to: 'dsl.js'
}]),
new HandlerPlugin({}), new HandlerPlugin({}),
new Css2jsonPlugin(), new Css2jsonPlugin(),
new InstVuePlugin(), new InstVuePlugin(),
...@@ -101,4 +104,4 @@ module.exports = { ...@@ -101,4 +104,4 @@ module.exports = {
}), }),
new NotifyPlugin() new NotifyPlugin()
] ]
} }
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const webpack = require('webpack')
const { const {
getPlatformScss, getPlatformScss,
...@@ -7,10 +8,6 @@ const { ...@@ -7,10 +8,6 @@ const {
nvueCssPreprocessOptions nvueCssPreprocessOptions
} = require('@dcloudio/uni-cli-shared') } = require('@dcloudio/uni-cli-shared')
const {
sassLoaderVersion
} = require('@dcloudio/uni-cli-shared/lib/scss')
const nvueStyleLoader = { const nvueStyleLoader = {
loader: '@dcloudio/vue-cli-plugin-hbuilderx/packages/webpack-uni-nvue-loader/lib/style' loader: '@dcloudio/vue-cli-plugin-hbuilderx/packages/webpack-uni-nvue-loader/lib/style'
} }
...@@ -20,27 +17,33 @@ const preprocessLoader = { ...@@ -20,27 +17,33 @@ const preprocessLoader = {
options: nvueCssPreprocessOptions options: nvueCssPreprocessOptions
} }
const options = {
sourceMap: false
}
const plugins = [
require('postcss-import')({
resolve (id, basedir, importOptions) {
if (id.startsWith('~@/')) {
return path.resolve(process.env.UNI_INPUT_DIR, id.substr(3))
} else if (id.startsWith('@/')) {
return path.resolve(process.env.UNI_INPUT_DIR, id.substr(2))
} else if (id.startsWith('/') && !id.startsWith('//')) {
return path.resolve(process.env.UNI_INPUT_DIR, id.substr(1))
}
return id
}
}),
require('@dcloudio/vue-cli-plugin-uni/packages/postcss')
]
if (webpack.version[0] > 4) {
options.postcssOptions = { plugins }
} else {
options.parser = require('postcss-comment')
options.plugins = plugins
}
const postcssLoader = { const postcssLoader = {
loader: 'postcss-loader', loader: 'postcss-loader',
options: { options
sourceMap: false,
parser: require('postcss-comment'),
plugins: [
require('postcss-import')({
resolve (id, basedir, importOptions) {
if (id.startsWith('~@/')) {
return path.resolve(process.env.UNI_INPUT_DIR, id.substr(3))
} else if (id.startsWith('@/')) {
return path.resolve(process.env.UNI_INPUT_DIR, id.substr(2))
} else if (id.startsWith('/') && !id.startsWith('//')) {
return path.resolve(process.env.UNI_INPUT_DIR, id.substr(1))
}
return id
}
}),
require('@dcloudio/vue-cli-plugin-uni/packages/postcss')
]
}
} }
// sass 全局变量 // sass 全局变量
...@@ -71,25 +74,15 @@ const sassLoader = { ...@@ -71,25 +74,15 @@ const sassLoader = {
} }
} }
if (sassLoaderVersion < 8) { scssLoader.options.prependData = sassData
scssLoader.options.data = sassData scssLoader.options.sassOptions = {
scssLoader.options.outputStyle = 'expanded' outputStyle: 'expanded'
}
sassLoader.options.data = sassData
sassLoader.options.outputStyle = 'expanded'
sassLoader.options.indentedSyntax = true
} else {
const name = sassLoaderVersion >= 9 ? 'additionalData' : 'prependData'
scssLoader.options[name] = sassData
scssLoader.options.sassOptions = {
outputStyle: 'expanded'
}
sassLoader.options[name] = sassData sassLoader.options.prependData = sassData
sassLoader.options.sassOptions = { sassLoader.options.sassOptions = {
outputStyle: 'expanded', outputStyle: 'expanded',
indentedSyntax: true indentedSyntax: true
}
} }
const lessLoader = { const lessLoader = {
...@@ -143,4 +136,4 @@ module.exports = [{ ...@@ -143,4 +136,4 @@ module.exports = [{
}, { }, {
test: /\.styl(us)?$/, test: /\.styl(us)?$/,
oneOf: createOneOf(stylusLoader) oneOf: createOneOf(stylusLoader)
}] }]
...@@ -3,6 +3,7 @@ const path = require('path') ...@@ -3,6 +3,7 @@ const path = require('path')
const webpack = require('webpack') const webpack = require('webpack')
const VueLoaderPlugin = require('@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/plugin') const VueLoaderPlugin = require('@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin')
const CopyWebpackPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
const TerserPlugin = require('terser-webpack-plugin') const TerserPlugin = require('terser-webpack-plugin')
const { const {
...@@ -112,7 +113,10 @@ if (process.env.NODE_ENV === 'development') { ...@@ -112,7 +113,10 @@ if (process.env.NODE_ENV === 'development') {
// const excludeModuleReg = /node_modules(?!(\/|\\).*(weex).*)/ // const excludeModuleReg = /node_modules(?!(\/|\\).*(weex).*)/
const rules = [{ const rules = [webpack.version[0] > 4 ? {
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
type: 'asset'
} : {
test: /\.(png|jpg|gif|ttf|eot|woff|woff2)$/i, test: /\.(png|jpg|gif|ttf|eot|woff|woff2)$/i,
use: [fileLoader] use: [fileLoader]
}, { }, {
...@@ -194,7 +198,7 @@ rules.unshift({ ...@@ -194,7 +198,7 @@ rules.unshift({
if (process.env.UNI_USING_V3_NATIVE) { if (process.env.UNI_USING_V3_NATIVE) {
try { try {
const automatorJson = require.resolve('@dcloudio/uni-automator/dist/automator.json') const automatorJson = require.resolve('@dcloudio/uni-automator/dist/automator.json')
plugins.push(new CopyWebpackPlugin([{ const patterns = [{
from: automatorJson, from: automatorJson,
to: '../.automator/' + (process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM) + to: '../.automator/' + (process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM) +
'/.automator.json', '/.automator.json',
...@@ -207,15 +211,16 @@ if (process.env.UNI_USING_V3_NATIVE) { ...@@ -207,15 +211,16 @@ if (process.env.UNI_USING_V3_NATIVE) {
} }
return '' return ''
} }
}])) }]
} catch (e) {} plugins.push(new CopyWebpackPlugin(CopyWebpackPluginVersion > 5 ? { patterns } : patterns))
} catch (e) { }
} }
if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) { if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
plugins.push(new WebpackUniMPPlugin()) plugins.push(new WebpackUniMPPlugin())
const assetsDir = 'static' const assetsDir = 'static'
const hybridDir = 'hybrid/html' const hybridDir = 'hybrid/html'
const array = [{ const patterns = [{
from: path.resolve(process.env.UNI_INPUT_DIR, assetsDir), from: path.resolve(process.env.UNI_INPUT_DIR, assetsDir),
to: assetsDir to: assetsDir
}] }]
...@@ -223,7 +228,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) { ...@@ -223,7 +228,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
if (!process.env.UNI_AUTOMATOR_WS_ENDPOINT) { if (!process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
const androidPrivacyPath = path.resolve(process.env.UNI_INPUT_DIR, 'androidPrivacy.json') const androidPrivacyPath = path.resolve(process.env.UNI_INPUT_DIR, 'androidPrivacy.json')
if (fs.existsSync(androidPrivacyPath)) { if (fs.existsSync(androidPrivacyPath)) {
array.push({ patterns.push({
from: androidPrivacyPath, from: androidPrivacyPath,
to: 'androidPrivacy.json' to: 'androidPrivacy.json'
}) })
...@@ -231,7 +236,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) { ...@@ -231,7 +236,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
} }
const hybridHtmlPath = path.resolve(process.env.UNI_INPUT_DIR, hybridDir) const hybridHtmlPath = path.resolve(process.env.UNI_INPUT_DIR, hybridDir)
if (fs.existsSync(hybridHtmlPath)) { if (fs.existsSync(hybridHtmlPath)) {
array.push({ patterns.push({
from: hybridHtmlPath, from: hybridHtmlPath,
to: hybridDir to: hybridDir
}) })
...@@ -242,7 +247,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) { ...@@ -242,7 +247,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
const assets = modules + module + '/' + assetsDir const assets = modules + module + '/' + assetsDir
const assetsPath = path.resolve(process.env.UNI_INPUT_DIR, assets) const assetsPath = path.resolve(process.env.UNI_INPUT_DIR, assets)
if (fs.existsSync(assetsPath)) { if (fs.existsSync(assetsPath)) {
array.push({ patterns.push({
from: assetsPath, from: assetsPath,
to: assets to: assets
}) })
...@@ -250,7 +255,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) { ...@@ -250,7 +255,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
const hybridHtml = modules + module + '/' + hybridDir const hybridHtml = modules + module + '/' + hybridDir
const hybridHtmlPath = path.resolve(process.env.UNI_INPUT_DIR, hybridHtml) const hybridHtmlPath = path.resolve(process.env.UNI_INPUT_DIR, hybridHtml)
if (fs.existsSync(hybridHtmlPath)) { if (fs.existsSync(hybridHtmlPath)) {
array.push({ patterns.push({
from: hybridHtmlPath, from: hybridHtmlPath,
to: hybridHtml to: hybridHtml
}) })
...@@ -258,12 +263,12 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) { ...@@ -258,12 +263,12 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
}) })
if (process.env.UNI_USING_NVUE_COMPILER) { if (process.env.UNI_USING_NVUE_COMPILER) {
array.push({ patterns.push({
from: path.resolve(getTemplatePath(), 'common'), from: path.resolve(getTemplatePath(), 'common'),
to: process.env.UNI_OUTPUT_DIR to: process.env.UNI_OUTPUT_DIR
}) })
} else if (process.env.UNI_USING_V3_NATIVE) { } else if (process.env.UNI_USING_V3_NATIVE) {
array.push({ patterns.push({
from: path.resolve(getTemplatePath(), 'weex'), from: path.resolve(getTemplatePath(), 'weex'),
to: process.env.UNI_OUTPUT_DIR to: process.env.UNI_OUTPUT_DIR
}) })
...@@ -275,7 +280,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) { ...@@ -275,7 +280,7 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
'weapp-tools/template/v8' 'weapp-tools/template/v8'
) )
} }
array.push({ patterns.push({
from: nativeTemplatePath, from: nativeTemplatePath,
to: process.env.UNI_OUTPUT_DIR to: process.env.UNI_OUTPUT_DIR
}, { }, {
...@@ -284,15 +289,17 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) { ...@@ -284,15 +289,17 @@ if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
'weapp-tools/template/common' 'weapp-tools/template/common'
), ),
to: process.env.UNI_OUTPUT_DIR, to: process.env.UNI_OUTPUT_DIR,
ignore: [ globOptions: {
'*.js', ignore: [
'*.json', '*.js',
'__uniapppicker.html', '*.json',
'__uniappview.html' '__uniapppicker.html',
] '__uniappview.html'
]
}
}) })
} }
plugins.push(new CopyWebpackPlugin(array)) plugins.push(new CopyWebpackPlugin(CopyWebpackPluginVersion > 5 ? { patterns } : patterns))
} }
try { try {
...@@ -305,7 +312,7 @@ try { ...@@ -305,7 +312,7 @@ try {
dir: process.env.UNI_INPUT_DIR dir: process.env.UNI_INPUT_DIR
})) }))
} }
} catch (e) {} } catch (e) { }
module.exports = function () { module.exports = function () {
return { return {
...@@ -322,8 +329,7 @@ module.exports = function () { ...@@ -322,8 +329,7 @@ module.exports = function () {
performance: { performance: {
hints: false hints: false
}, },
optimization: { optimization: Object.assign({
namedModules: false,
minimizer: [ minimizer: [
new TerserPlugin({ new TerserPlugin({
terserOptions: { terserOptions: {
...@@ -333,7 +339,7 @@ module.exports = function () { ...@@ -333,7 +339,7 @@ module.exports = function () {
} }
}) })
] ]
}, }, webpack.version[0] > 4 ? {} : { namedModules: false }),
output: { output: {
path: process.env.UNI_OUTPUT_DIR, path: process.env.UNI_OUTPUT_DIR,
filename: '[name].js' filename: '[name].js'
...@@ -377,7 +383,7 @@ module.exports = function () { ...@@ -377,7 +383,7 @@ module.exports = function () {
reasons: true, reasons: true,
errorDetails: true errorDetails: true
}, },
node: { node: webpack.version[0] > 4 ? false : {
global: false, global: false,
Buffer: false, Buffer: false,
__filename: false, __filename: false,
......
...@@ -14,13 +14,10 @@ class WebpackAppPlusNVuePlugin { ...@@ -14,13 +14,10 @@ class WebpackAppPlusNVuePlugin {
const changedFiles = [] const changedFiles = []
compiler.hooks.emit.tapAsync('webpack-uni-nvue', (compilation, callback) => { compiler.hooks.emit.tapAsync('webpack-uni-nvue', (compilation, callback) => {
changedFiles.length = 0 changedFiles.length = 0
const changedChunks = compilation.chunks.filter(chunk => { compilation.chunks.forEach(chunk => {
const oldVersion = chunkVersions[chunk.name] const oldVersion = chunkVersions[chunk.name]
chunkVersions[chunk.name] = chunk.hash chunkVersions[chunk.name] = chunk.hash
return chunk.hash !== oldVersion if (chunk.hash !== oldVersion && Array.isArray(chunk.files)) {
})
changedChunks.map(chunk => {
if (Array.isArray(chunk.files)) {
chunk.files.forEach(file => { chunk.files.forEach(file => {
!changedFiles.includes(file) && (changedFiles.push(file)) !changedFiles.includes(file) && (changedFiles.push(file))
}) })
......
...@@ -44,13 +44,10 @@ class WebpackAppPlusPlugin { ...@@ -44,13 +44,10 @@ class WebpackAppPlusPlugin {
}) })
compiler.hooks.emit.tapAsync('WebpackAppPlusPlugin', (compilation, callback) => { compiler.hooks.emit.tapAsync('WebpackAppPlusPlugin', (compilation, callback) => {
const changedChunks = compilation.chunks.filter(chunk => { compilation.chunks.forEach(chunk => {
const oldVersion = chunkVersions[chunk.name] const oldVersion = chunkVersions[chunk.name]
chunkVersions[chunk.name] = chunk.hash chunkVersions[chunk.name] = chunk.hash
return chunk.hash !== oldVersion if (chunk.hash !== oldVersion && Array.isArray(chunk.files)) {
})
changedChunks.map(chunk => {
if (Array.isArray(chunk.files)) {
chunk.files.forEach(file => { chunk.files.forEach(file => {
if (isAppService) { if (isAppService) {
!serviceChangedFiles.includes(file) && (serviceChangedFiles.push(file)) !serviceChangedFiles.includes(file) && (serviceChangedFiles.push(file))
......
const path = require('path') const path = require('path')
const webpack = require('webpack')
const { const {
runByHBuilderX, runByHBuilderX,
...@@ -73,7 +74,7 @@ module.exports = (api, options) => { ...@@ -73,7 +74,7 @@ module.exports = (api, options) => {
process.env.VUE_CLI_BUILD_TARGET = args.target process.env.VUE_CLI_BUILD_TARGET = args.target
if (args['sourcemap']) process.env.SOURCEMAP = args['sourcemap'] if (args.sourcemap) process.env.SOURCEMAP = args.sourcemap
await build(args, api, options) await build(args, api, options)
...@@ -98,14 +99,18 @@ function getWebpackConfig (api, args, options) { ...@@ -98,14 +99,18 @@ function getWebpackConfig (api, args, options) {
if (args.minimize && process.env.NODE_ENV !== 'production') { if (args.minimize && process.env.NODE_ENV !== 'production') {
modifyConfig(webpackConfig, config => { modifyConfig(webpackConfig, config => {
config.optimization.minimize = true config.optimization.minimize = true
config.optimization.namedModules = false if (webpack.version[0] <= 4) {
config.optimization.namedModules = false
}
}) })
} else { } else {
modifyConfig(webpackConfig, config => { modifyConfig(webpackConfig, config => {
if (!config.optimization) { if (!config.optimization) {
config.optimization = {} config.optimization = {}
} }
config.optimization.namedModules = false if (webpack.version[0] <= 4) {
config.optimization.namedModules = false
}
}) })
} }
return webpackConfig return webpackConfig
...@@ -131,7 +136,6 @@ function getWebpackConfigs (api, args, options) { ...@@ -131,7 +136,6 @@ function getWebpackConfigs (api, args, options) {
async function build (args, api, options) { async function build (args, api, options) {
const fs = require('fs-extra') const fs = require('fs-extra')
const chalk = require('chalk') const chalk = require('chalk')
const webpack = require('webpack')
const { const {
log, log,
......
...@@ -37,7 +37,7 @@ module.exports = (api, options) => { ...@@ -37,7 +37,7 @@ module.exports = (api, options) => {
const url = require('url') const url = require('url')
const path = require('path') const path = require('path')
const chalk = require('chalk') const { chalk } = require('@vue/cli-shared-utils')
const webpack = require('webpack') const webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server') const WebpackDevServer = require('webpack-dev-server')
const portfinder = require('portfinder') const portfinder = require('portfinder')
...@@ -139,48 +139,98 @@ module.exports = (api, options) => { ...@@ -139,48 +139,98 @@ module.exports = (api, options) => {
const compiler = webpack(webpackConfig) const compiler = webpack(webpackConfig)
// create server // create server
const server = new WebpackDevServer(compiler, Object.assign({ let server
clientLogLevel: 'none', if (webpack.version[0] > 4) {
historyApiFallback: { server = new WebpackDevServer(Object.assign({
disableDotRule: true, historyApiFallback: {
rewrites: [{ disableDotRule: true,
from: /./, rewrites: [{
to: path.posix.join(options.publicPath, 'index.html') from: /./,
}] to: path.posix.join(options.publicPath, 'index.html')
}, }]
contentBase: api.resolve('public'), },
watchContentBase: !isProduction, hot: !isProduction,
hot: !isProduction, compress: isProduction,
quiet: true, static: {
compress: isProduction, directory: api.resolve('public'),
publicPath: options.publicPath, publicPath: options.publicPath,
overlay: isProduction // TODO disable this watch: !isProduction,
? false : { ...projectDevServerOptions.static
warnings: false, },
errors: true client: {
logging: 'none',
overlay: isProduction // TODO disable this
? false
: { warnings: false, errors: true },
progress: !process.env.VUE_CLI_TEST,
...projectDevServerOptions.client
} }
}, projectDevServerOptions, { }, projectDevServerOptions, {
https: useHttps, https: useHttps,
proxy: proxySettings, proxy: proxySettings,
before (app, server) { setupMiddlewares (middlewares, devServer) {
// launch editor support.
// this works with vue-devtools & @vue/cli-overlay
devServer.app.use('/__open-in-editor', launchEditorMiddleware(() => console.log(
'To specify an editor, specify the EDITOR env variable or ' +
'add "editor" field to your Vue project config.\n'
)))
// allow other plugins to register middlewares, e.g. PWA
// todo: migrate to the new API interface
api.service.devServerConfigFns.forEach(fn => fn(devServer.app, devServer))
if (projectDevServerOptions.setupMiddlewares) {
return projectDevServerOptions.setupMiddlewares(middlewares, devServer)
}
return middlewares
}
}), compiler)
} else {
server = new WebpackDevServer(compiler, Object.assign({
clientLogLevel: 'none',
historyApiFallback: {
disableDotRule: true,
rewrites: [{
from: /./,
to: path.posix.join(options.publicPath, 'index.html')
}]
},
contentBase: api.resolve('public'),
watchContentBase: !isProduction,
hot: !isProduction,
quiet: true,
compress: isProduction,
publicPath: options.publicPath,
overlay: isProduction // TODO disable this
? false : {
warnings: false,
errors: true
}
}, projectDevServerOptions, {
https: useHttps,
proxy: proxySettings,
before (app, server) {
// launch editor support. // launch editor support.
// this works with vue-devtools & @vue/cli-overlay // this works with vue-devtools & @vue/cli-overlay
app.use('/__open-in-editor', launchEditorMiddleware(() => console.log( app.use('/__open-in-editor', launchEditorMiddleware(() => console.log(
'To specify an editor, sepcify the EDITOR env variable or ' + 'To specify an editor, sepcify the EDITOR env variable or ' +
'add "editor" field to your Vue project config.\n' 'add "editor" field to your Vue project config.\n'
))) )))
// allow other plugins to register middlewares, e.g. PWA // allow other plugins to register middlewares, e.g. PWA
api.service.devServerConfigFns.forEach(fn => fn(app, server)) api.service.devServerConfigFns.forEach(fn => fn(app, server))
// apply in project middlewares // apply in project middlewares
projectDevServerOptions.before && projectDevServerOptions.before(app, projectDevServerOptions.before && projectDevServerOptions.before(app,
server) server)
} }
})) }))
}
; ;
['SIGINT', 'SIGTERM'].forEach(signal => { ['SIGINT', 'SIGTERM'].forEach(signal => {
process.on(signal, () => { process.on(signal, () => {
server.close(() => { server[webpack.version[0] > 4 ? 'stopCallback' : 'close'](() => {
process.exit(0) process.exit(0)
}) })
}) })
...@@ -192,7 +242,7 @@ module.exports = (api, options) => { ...@@ -192,7 +242,7 @@ module.exports = (api, options) => {
process.stdin.on('data', data => { process.stdin.on('data', data => {
if (data.toString() === 'close') { if (data.toString() === 'close') {
console.log('got close signal!') console.log('got close signal!')
server.close(() => { server[webpack.version[0] > 4 ? 'stopCallback' : 'close'](() => {
process.exit(0) process.exit(0)
}) })
} }
...@@ -303,11 +353,15 @@ module.exports = (api, options) => { ...@@ -303,11 +353,15 @@ module.exports = (api, options) => {
server.showStatus = function () {} server.showStatus = function () {}
} }
server.listen(port, host, err => { if (webpack.version[0] > 4) {
if (err) { server.start().catch(err => reject(err))
reject(err) } else {
} server.listen(port, host, err => {
}) if (err) {
reject(err)
}
})
}
}) })
}) })
} }
......
...@@ -70,7 +70,11 @@ const v3 = { ...@@ -70,7 +70,11 @@ const v3 = {
webpackConfig.optimization = {} webpackConfig.optimization = {}
} }
// disable noEmitOnErrors // disable noEmitOnErrors
webpackConfig.optimization.noEmitOnErrors = false if (webpack.version[0] > 4) {
webpackConfig.optimization.emitOnErrors = true
} else {
webpackConfig.optimization.noEmitOnErrors = false
}
if (isAppService) { if (isAppService) {
webpackConfig.optimization.runtimeChunk = { webpackConfig.optimization.runtimeChunk = {
...@@ -134,7 +138,8 @@ const v3 = { ...@@ -134,7 +138,8 @@ const v3 = {
output: { output: {
filename: '[name].js', filename: '[name].js',
chunkFilename: '[id].js', chunkFilename: '[id].js',
globalObject: 'this' // webpack5 use strict
globalObject: webpack.version[0] > 4 ? '(new Function("return this")())' : 'this'
}, },
performance: { performance: {
hints: false hints: false
...@@ -158,7 +163,7 @@ const v3 = { ...@@ -158,7 +163,7 @@ const v3 = {
compiler: vueLoader.compiler, compiler: vueLoader.compiler,
before: [ before: [
beforeCode + require('../util').getAutomatorCode() + statCode + pushCode + uniCloudCode + beforeCode + require('../util').getAutomatorCode() + statCode + pushCode + uniCloudCode +
getGlobalUsingComponentsCode() getGlobalUsingComponentsCode()
] ]
} }
}] }]
...@@ -260,6 +265,8 @@ const v3 = { ...@@ -260,6 +265,8 @@ const v3 = {
}) })
} }
webpackConfig.plugin('vue-loader').use(require(vueLoader.loader).VueLoaderPlugin)
webpackConfig.plugins.delete('hmr') webpackConfig.plugins.delete('hmr')
webpackConfig.plugins.delete('html') webpackConfig.plugins.delete('html')
webpackConfig.plugins.delete('copy') webpackConfig.plugins.delete('copy')
......
const path = require('path') const path = require('path')
const webpack = require('webpack')
const {
sassLoaderVersion
} = require('@dcloudio/uni-cli-shared/lib/scss')
const { const {
getPartialIdentifier getPartialIdentifier
...@@ -23,11 +20,38 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) { ...@@ -23,11 +20,38 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) {
const urlLoader = require('@dcloudio/uni-cli-shared/lib/url-loader') const urlLoader = require('@dcloudio/uni-cli-shared/lib/url-loader')
const staticTypes = ['images', 'media', 'fonts'] const staticTypes = ['images', 'media', 'fonts']
staticTypes.forEach(staticType => { staticTypes.forEach(staticType => {
webpackConfig.module const newOptions = urlLoader.options()
.rule(staticType) if (webpack.version[0] > 4) {
.use('url-loader') if ('limit' in newOptions) {
.loader(urlLoader.loader) webpackConfig.module.rule(staticType).parser({
.tap(options => Object.assign(options, urlLoader.options())) dataUrlCondition: {
maxSize: newOptions.limit
}
})
}
if (newOptions.fallback && newOptions.fallback.options) {
const generator = {}
const oldOptions = newOptions.fallback.options
const keys = ['publicPath', 'outputPath']
keys.forEach(key => {
generator[key] = pathData => {
const outputPath = oldOptions.outputPath(null, pathData.module.request)
const basename = path.basename(outputPath)
return outputPath.substring(0, outputPath.length - basename.length)
}
})
generator.filename = pathData => {
return path.basename(pathData.module.request)
}
webpackConfig.module.rule(staticType).set('generator', generator)
}
} else {
webpackConfig.module
.rule(staticType)
.use('url-loader')
.loader(urlLoader.loader)
.tap(options => Object.assign(options, newOptions))
}
}) })
// 条件编译 vue 文件统一直接过滤html,js,css三种类型,单独资源文件引用各自过滤 // 条件编译 vue 文件统一直接过滤html,js,css三种类型,单独资源文件引用各自过滤
...@@ -56,6 +80,18 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) { ...@@ -56,6 +80,18 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) {
)) ))
.before('css-loader') .before('css-loader')
} }
if (webpack.version[0] > 4) {
langRule.oneOf(type)
.use('css-loader')
.tap(options => {
options.url = {
filter: function (url) {
return url[0] !== '/'
}
}
return options
})
}
langRule.oneOf(type) langRule.oneOf(type)
.use('uniapp-preprocss') .use('uniapp-preprocss')
.loader(resolve('packages/webpack-preprocess-loader')) .loader(resolve('packages/webpack-preprocess-loader'))
...@@ -72,21 +108,19 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) { ...@@ -72,21 +108,19 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) {
}) })
}) })
if (sassLoaderVersion >= 8) { // check indentedSyntax // vue cli 3 and sass-loader 8
// vue cli 3 and sass-loader 8 cssTypes.forEach(type => {
cssTypes.forEach(type => { webpackConfig.module.rule('sass').oneOf(type).use('sass-loader').tap(options => {
webpackConfig.module.rule('sass').oneOf(type).use('sass-loader').tap(options => { if (options.indentedSyntax) {
if (options.indentedSyntax) { if (!options.sassOptions) {
if (!options.sassOptions) { options.sassOptions = {}
options.sassOptions = {}
}
options.sassOptions.indentedSyntax = true
delete options.indentedSyntax
} }
return options options.sassOptions.indentedSyntax = true
}) delete options.indentedSyntax
}
return options
}) })
} })
platformOptions.chainWebpack(webpackConfig, vueOptions, api) platformOptions.chainWebpack(webpackConfig, vueOptions, api)
// define // define
......
...@@ -34,7 +34,7 @@ module.exports = function custom (argv) { ...@@ -34,7 +34,7 @@ module.exports = function custom (argv) {
clean: false, clean: false,
subpackage: argv.subpackage, subpackage: argv.subpackage,
plugin: argv.plugin, plugin: argv.plugin,
sourcemap: argv['sourcemap'], sourcemap: argv.sourcemap
}).catch(err => { }).catch(err => {
console.error(err) console.error(err)
process.exit(1) process.exit(1)
......
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const webpack = require('webpack') const webpack = require('webpack')
const RuleSet = require('webpack/lib/RuleSet')
const CopyWebpackPlugin = require('copy-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin')
const CopyWebpackPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
const merge = require('webpack-merge') const merge = require('webpack-merge')
...@@ -39,12 +39,44 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt ...@@ -39,12 +39,44 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt
return (rule, i) => { return (rule, i) => {
const clone = Object.assign({}, rule) const clone = Object.assign({}, rule)
delete clone.include delete clone.include
const normalized = RuleSet.normalizeRule(clone, {}, '') if (webpack.version[0] > 4) {
return ( const BasicEffectRulePlugin = require('webpack/lib/rules/BasicEffectRulePlugin')
!rule.enforce && const BasicMatcherRulePlugin = require('webpack/lib/rules/BasicMatcherRulePlugin')
const RuleSetCompiler = require('webpack/lib/rules/RuleSetCompiler')
const UseEffectRulePlugin = require('webpack/lib/rules/UseEffectRulePlugin')
const ruleSetCompiler = new RuleSetCompiler([
new BasicMatcherRulePlugin('test', 'resource'),
new BasicMatcherRulePlugin('include', 'resource'),
new BasicMatcherRulePlugin('exclude', 'resource', true),
new BasicMatcherRulePlugin('resource'),
new BasicMatcherRulePlugin('conditions'),
new BasicMatcherRulePlugin('resourceQuery'),
new BasicMatcherRulePlugin('realResource'),
new BasicMatcherRulePlugin('issuer'),
new BasicMatcherRulePlugin('compiler'),
new BasicEffectRulePlugin('type'),
new BasicEffectRulePlugin('sideEffects'),
new BasicEffectRulePlugin('parser'),
new BasicEffectRulePlugin('resolve'),
new BasicEffectRulePlugin('generator'),
new UseEffectRulePlugin()
])
const ruleSet = ruleSetCompiler.compile([{
rules: [clone]
}])
const rules = ruleSet.exec({
resource: fakeFile
})
return rules.length > 0 && rule.use
} else {
const RuleSet = require('webpack/lib/RuleSet')
const normalized = RuleSet.normalizeRule(clone, {}, '')
return (
!rule.enforce &&
normalized.resource && normalized.resource &&
normalized.resource(fakeFile) normalized.resource(fakeFile)
) )
}
} }
} }
...@@ -152,13 +184,15 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt ...@@ -152,13 +184,15 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt
if (Array.isArray(uses)) { if (Array.isArray(uses)) {
if (uses.find(use => babelLoaderRe.test(use.loader))) { if (uses.find(use => babelLoaderRe.test(use.loader))) {
const index = uses.findIndex(use => cacheLoaderRe.test(use.loader)) const index = uses.findIndex(use => cacheLoaderRe.test(use.loader))
if (process.env.UNI_USING_CACHE) { if (index >= 0) {
Object.assign(uses[index].options, api.genCacheConfig( if (process.env.UNI_USING_CACHE) {
'babel-loader/' + process.env.UNI_PLATFORM, Object.assign(uses[index].options, api.genCacheConfig(
getPartialIdentifier() 'babel-loader/' + process.env.UNI_PLATFORM,
)) getPartialIdentifier()
} else { ))
uses.splice(index, 1) } else {
uses.splice(index, 1)
}
} }
} }
} }
...@@ -198,12 +232,13 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt ...@@ -198,12 +232,13 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt
vueOptions.pluginOptions['uni-app-plus'].view vueOptions.pluginOptions['uni-app-plus'].view
if (!isAppView) { // app-plus view不需要copy if (!isAppView) { // app-plus view不需要copy
plugins.push(new CopyWebpackPlugin(getCopyWebpackPluginOptions(manifestPlatformOptions, vueOptions))) const patterns = getCopyWebpackPluginOptions(manifestPlatformOptions, vueOptions)
plugins.push(new CopyWebpackPlugin(CopyWebpackPluginVersion > 5 ? { patterns } : patterns))
} }
if (!process.env.UNI_SUBPACKGE || !process.env.UNI_MP_PLUGIN) { if (!process.env.UNI_SUBPACKGE || !process.env.UNI_MP_PLUGIN) {
try { try {
const automatorJson = require.resolve('@dcloudio/uni-automator/dist/automator.json') const automatorJson = require.resolve('@dcloudio/uni-automator/dist/automator.json')
plugins.push(new CopyWebpackPlugin([{ const patterns = [{
from: automatorJson, from: automatorJson,
to: '../.automator/' + (process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM) + to: '../.automator/' + (process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM) +
'/.automator.json', '/.automator.json',
...@@ -216,8 +251,9 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt ...@@ -216,8 +251,9 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt
} }
return '' return ''
} }
}])) }]
} catch (e) {} plugins.push(new CopyWebpackPlugin(CopyWebpackPluginVersion > 5 ? { patterns } : patterns))
} catch (e) { }
} }
if (process.UNI_SCRIPT_ENV && Object.keys(process.UNI_SCRIPT_ENV).length) { if (process.UNI_SCRIPT_ENV && Object.keys(process.UNI_SCRIPT_ENV).length) {
...@@ -289,8 +325,7 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt ...@@ -289,8 +325,7 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt
noSources: true, noSources: true,
append: false append: false
} }
if (isInHBuilderX && process.env.SOURCEMAP_PATH) if (isInHBuilderX && process.env.SOURCEMAP_PATH) { sourceMapOptions.filename = process.env.SOURCEMAP_PATH }
sourceMapOptions.filename = process.env.SOURCEMAP_PATH
if (useEvalSourceMap || useSourceMap) { if (useEvalSourceMap || useSourceMap) {
plugins.push(sourceMap.createSourceMapDevToolPlugin(!sourceMapOptions.filename, sourceMapOptions)) plugins.push(sourceMap.createSourceMapDevToolPlugin(!sourceMapOptions.filename, sourceMapOptions))
} }
...@@ -302,7 +337,7 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt ...@@ -302,7 +337,7 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt
} }
} }
} }
try { try {
if (process.env.UNI_HBUILDERX_PLUGINS) { if (process.env.UNI_HBUILDERX_PLUGINS) {
require(path.resolve(process.env.UNI_HBUILDERX_PLUGINS, 'uni_helpers/lib/bytenode')) require(path.resolve(process.env.UNI_HBUILDERX_PLUGINS, 'uni_helpers/lib/bytenode'))
......
...@@ -7,6 +7,7 @@ const { ...@@ -7,6 +7,7 @@ const {
initI18nOptions initI18nOptions
} = require('@dcloudio/uni-cli-shared/lib/i18n') } = require('@dcloudio/uni-cli-shared/lib/i18n')
const assetsDir = 'static' const assetsDir = 'static'
const CopyWebpackPluginVersion = Number(require('copy-webpack-plugin/package.json').version.split('.')[0])
function getAssetsCopyOption (from, options = {}) { function getAssetsCopyOption (from, options = {}) {
if (path.isAbsolute(from)) { if (path.isAbsolute(from)) {
...@@ -42,7 +43,9 @@ function getAssetsCopyOptions (assetsDir) { ...@@ -42,7 +43,9 @@ function getAssetsCopyOptions (assetsDir) {
const copyOptions = [] const copyOptions = []
// 主包静态资源 // 主包静态资源
const mainAssetsCopyOption = getAssetsCopyOption(assetsDir, { const mainAssetsCopyOption = getAssetsCopyOption(assetsDir, CopyWebpackPluginVersion > 5 ? {
globOptions: { ignore }
} : {
ignore ignore
}) })
if (mainAssetsCopyOption) { if (mainAssetsCopyOption) {
...@@ -51,11 +54,11 @@ function getAssetsCopyOptions (assetsDir) { ...@@ -51,11 +54,11 @@ function getAssetsCopyOptions (assetsDir) {
// 分包静态资源 // 分包静态资源
process.UNI_SUBPACKAGES && process.UNI_SUBPACKAGES &&
Object.keys(process.UNI_SUBPACKAGES).forEach(root => { Object.keys(process.UNI_SUBPACKAGES).forEach(root => {
const subAssetsCopyOption = getAssetsCopyOption( const subAssetsCopyOption = getAssetsCopyOption(path.join(root, assetsDir), CopyWebpackPluginVersion > 5 ? {
path.join(root, assetsDir), { globOptions: { ignore }
ignore } : {
} ignore
) })
if (subAssetsCopyOption) { if (subAssetsCopyOption) {
copyOptions.push(subAssetsCopyOption) copyOptions.push(subAssetsCopyOption)
} }
...@@ -91,10 +94,8 @@ function getCopyWebpackPluginOptions (platformOptions, vueOptions) { ...@@ -91,10 +94,8 @@ function getCopyWebpackPluginOptions (platformOptions, vueOptions) {
if (process.env.UNI_PLATFORM === 'app-plus' && !process.env.UNI_AUTOMATOR_WS_ENDPOINT) { if (process.env.UNI_PLATFORM === 'app-plus' && !process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
copyOptions.push({ copyOptions.push({
from: path.resolve(process.env.UNI_INPUT_DIR, 'android*.json'), from: path.resolve(process.env.UNI_INPUT_DIR, 'android*.json'),
to: '[name].[ext]', to: `[name]${CopyWebpackPluginVersion > 5 ? '' : '.'}[ext]`,
globOptions: { noErrorOnMissing: true,
ignored: require('./util').getWatchOptions().ignored
},
transform (content, path) { transform (content, path) {
if (path.endsWith('androidPrivacy.json')) { if (path.endsWith('androidPrivacy.json')) {
const options = initI18nOptions( const options = initI18nOptions(
...@@ -118,4 +119,4 @@ function getCopyWebpackPluginOptions (platformOptions, vueOptions) { ...@@ -118,4 +119,4 @@ function getCopyWebpackPluginOptions (platformOptions, vueOptions) {
module.exports = { module.exports = {
assetsDir, assetsDir,
getCopyWebpackPluginOptions getCopyWebpackPluginOptions
} }
const { const {
getPlatformCssnano getPlatformCssnano
} = require('@dcloudio/uni-cli-shared') } = require('@dcloudio/uni-cli-shared')
const webpack = require('webpack')
module.exports = function initCssnanoOptions (webpackConfig) { module.exports = function initCssnanoOptions (webpackConfig) {
const module = webpackConfig.module const module = webpackConfig.module
// TODO 临时 hack calc:false 看看 vue cli 后续是否开放 cssnano 的配置 // TODO 临时 hack calc:false 看看 vue cli 后续是否开放 cssnano 的配置
const cssnanoOptions = { const cssnanoOptions = {
sourceMap: false, sourceMap: false
plugins: [require('cssnano')({ }
preset: ['default', getPlatformCssnano()]
})] const plugins = [require('cssnano')({
preset: ['default', getPlatformCssnano()]
})]
// TODO postcss-loader version > 4
if (webpack.version[0] > 4) {
cssnanoOptions.postcssOptions = { plugins }
} else {
cssnanoOptions.plugins = plugins
} }
module.rule('css').oneOf('vue-modules').use('cssnano').loader('postcss-loader').options(cssnanoOptions) module.rule('css').oneOf('vue-modules').use('cssnano').loader('postcss-loader').options(cssnanoOptions)
......
...@@ -160,9 +160,13 @@ module.exports = { ...@@ -160,9 +160,13 @@ module.exports = {
}, },
plugins, plugins,
optimization: { optimization: {
moduleIds: 'hashed' moduleIds: webpack.version[0] > 4 ? 'deterministic' : 'hashed'
}, },
devServer: { devServer: webpack.version[0] > 4 ? {
watchFiles: {
options: require('../util').getWatchOptions()
}
} : {
watchOptions: require('../util').getWatchOptions() watchOptions: require('../util').getWatchOptions()
} }
} }
......
...@@ -157,7 +157,11 @@ module.exports = { ...@@ -157,7 +157,11 @@ module.exports = {
webpackConfig.optimization = {} webpackConfig.optimization = {}
} }
// disable noEmitOnErrors // disable noEmitOnErrors
webpackConfig.optimization.noEmitOnErrors = false if (webpack.version[0] > 4) {
webpackConfig.optimization.emitOnErrors = true
} else {
webpackConfig.optimization.noEmitOnErrors = false
}
webpackConfig.optimization.runtimeChunk = { webpackConfig.optimization.runtimeChunk = {
name: 'common/runtime' name: 'common/runtime'
...@@ -300,23 +304,30 @@ ${globalEnv}.__webpack_require_UNI_MP_PLUGIN__ = __webpack_require__;` ...@@ -300,23 +304,30 @@ ${globalEnv}.__webpack_require_UNI_MP_PLUGIN__ = __webpack_require__;`
process.env.NODE_ENV === 'production' && process.env.NODE_ENV === 'production' &&
process.env.UNI_PLATFORM !== 'app-plus' process.env.UNI_PLATFORM !== 'app-plus'
) { ) {
const OptimizeCssnanoPlugin = require('../../packages/@intervolga/optimize-cssnano-plugin/index.js') // webpack5 不再使用 OptimizeCssnanoPlugin,改用 CssMinimizerPlugin
webpackConfig.plugin('optimize-css') if (webpack.version[0] > 4) {
.init((Plugin, args) => new OptimizeCssnanoPlugin({ webpackConfig.optimization.minimizer('css').tap(args => {
sourceMap: false, args[0].test = new RegExp(`\\${styleExt}$`)
filter (assetName) { return args
return path.extname(assetName) === styleExt })
}, } else {
cssnanoOptions: { const OptimizeCssnanoPlugin = require('../../packages/@intervolga/optimize-cssnano-plugin/index.js')
preset: [ webpackConfig.plugin('optimize-css')
'default', .init((Plugin, args) => new OptimizeCssnanoPlugin({
Object.assign({}, getPlatformCssnano(), { sourceMap: false,
discardComments: true filter (assetName) {
}) return path.extname(assetName) === styleExt
] },
} cssnanoOptions: {
preset: [
})) 'default',
Object.assign({}, getPlatformCssnano(), {
discardComments: true
})
]
}
}))
}
} }
if (process.env.UNI_SUBPACKGE || process.env.UNI_MP_PLUGIN) { if (process.env.UNI_SUBPACKGE || process.env.UNI_MP_PLUGIN) {
......
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const webpack = require('webpack')
const isWin = /^win/.test(process.platform) const isWin = /^win/.test(process.platform)
...@@ -23,11 +24,11 @@ module.exports = function initOptions (options) { ...@@ -23,11 +24,11 @@ module.exports = function initOptions (options) {
options.transpileDependencies.push(genTranspileDepRegex(path.resolve(process.env.UNI_INPUT_DIR, 'node_modules'))) options.transpileDependencies.push(genTranspileDepRegex(path.resolve(process.env.UNI_INPUT_DIR, 'node_modules')))
options.transpileDependencies.push('@dcloudio/uni-' + process.env.UNI_PLATFORM) options.transpileDependencies.push('@dcloudio/uni-' + process.env.UNI_PLATFORM)
options.transpileDependencies.push('@dcloudio/uni-i18n') options.transpileDependencies.push('@dcloudio/uni-i18n')
options.transpileDependencies.push('@dcloudio/uni-stat') options.transpileDependencies.push('@dcloudio/uni-stat')
options.transpileDependencies.push('@dcloudio/uni-push') options.transpileDependencies.push('@dcloudio/uni-push')
options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-app') options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-app')
options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-cloud') options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-cloud')
options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-stat') options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-stat')
options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-push') options.transpileDependencies.push('@dcloudio/vue-cli-plugin-uni/packages/uni-push')
if (process.env.UNI_PLATFORM !== 'mp-weixin') { // mp runtime if (process.env.UNI_PLATFORM !== 'mp-weixin') { // mp runtime
...@@ -59,8 +60,14 @@ module.exports = function initOptions (options) { ...@@ -59,8 +60,14 @@ module.exports = function initOptions (options) {
options.css.loaderOptions.sass = {} options.css.loaderOptions.sass = {}
} }
if (!options.css.loaderOptions.postcss.config) { if (webpack.version[0] > 4) {
options.css.loaderOptions.postcss.config = {} if (!options.css.loaderOptions.postcss.postcssOptions) {
options.css.loaderOptions.postcss.postcssOptions = {}
}
} else {
if (!options.css.loaderOptions.postcss.config) {
options.css.loaderOptions.postcss.config = {}
}
} }
// sass 全局变量 // sass 全局变量
...@@ -85,9 +92,10 @@ module.exports = function initOptions (options) { ...@@ -85,9 +92,10 @@ module.exports = function initOptions (options) {
} }
options.css.loaderOptions.sass.prependData = sassData options.css.loaderOptions.sass.prependData = sassData
const userPostcssConfigPath = path.resolve(process.env.UNI_INPUT_DIR, 'postcss.config.js') const userPostcssConfigPath = path.resolve(process.env.UNI_INPUT_DIR, 'postcss.config.js')
if (fs.existsSync(userPostcssConfigPath)) { const configPath = fs.existsSync(userPostcssConfigPath) ? userPostcssConfigPath : path.resolve(process.env.UNI_CLI_CONTEXT, 'postcss.config.js')
options.css.loaderOptions.postcss.config.path = userPostcssConfigPath if (webpack.version[0] > 4) {
options.css.loaderOptions.postcss.postcssOptions.config = configPath
} else { } else {
options.css.loaderOptions.postcss.config.path = path.resolve(process.env.UNI_CLI_CONTEXT, 'postcss.config.js') options.css.loaderOptions.postcss.config.path = configPath
} }
} }
...@@ -20,7 +20,6 @@ ...@@ -20,7 +20,6 @@
"@dcloudio/uni-stat": "^2.0.1-alpha-35420220804003", "@dcloudio/uni-stat": "^2.0.1-alpha-35420220804003",
"buffer-json": "^2.0.0", "buffer-json": "^2.0.0",
"clone-deep": "^4.0.1", "clone-deep": "^4.0.1",
"copy-webpack-plugin": "^5.1.1",
"cross-env": "^5.2.0", "cross-env": "^5.2.0",
"envinfo": "^6.0.1", "envinfo": "^6.0.1",
"hash-sum": "^1.0.2", "hash-sum": "^1.0.2",
...@@ -29,7 +28,6 @@ ...@@ -29,7 +28,6 @@
"mkdirp": "^0.5.1", "mkdirp": "^0.5.1",
"module-alias": "^2.1.0", "module-alias": "^2.1.0",
"neo-async": "^2.6.1", "neo-async": "^2.6.1",
"postcss": "^7.0.7",
"postcss-import": "^12.0.1", "postcss-import": "^12.0.1",
"postcss-selector-parser": "^5.0.0", "postcss-selector-parser": "^5.0.0",
"postcss-value-parser": "^3.3.1", "postcss-value-parser": "^3.3.1",
...@@ -39,5 +37,9 @@ ...@@ -39,5 +37,9 @@
"wrap-loader": "^0.2.0", "wrap-loader": "^0.2.0",
"xregexp": "4.0.0" "xregexp": "4.0.0"
}, },
"peerDependencies": {
"copy-webpack-plugin": ">=5",
"postcss": ">=7"
},
"gitHead": "4a974e44466ae58194372e446299cf83c7a3ad2c" "gitHead": "4a974e44466ae58194372e446299cf83c7a3ad2c"
} }
...@@ -36,6 +36,8 @@ module.exports.pitch = function (remainingRequest) { ...@@ -36,6 +36,8 @@ module.exports.pitch = function (remainingRequest) {
'', '',
'// load the styles', '// load the styles',
'var content = require(' + request + ');', 'var content = require(' + request + ');',
// get default export if list is an ES Module (CSS Loader v4+)
"if(content.__esModule) content = content.default;",
// content list format is [id, css, media, sourceMap] // content list format is [id, css, media, sourceMap]
"if(typeof content === 'string') content = [[module.id, content, '']];", "if(typeof content === 'string') content = [[module.id, content, '']];",
'if(content.locals) module.exports = content.locals;' 'if(content.locals) module.exports = content.locals;'
...@@ -66,6 +68,7 @@ module.exports.pitch = function (remainingRequest) { ...@@ -66,6 +68,7 @@ module.exports.pitch = function (remainingRequest) {
' if(!content.locals) {', ' if(!content.locals) {',
' module.hot.accept(' + request + ', function() {', ' module.hot.accept(' + request + ', function() {',
' var newContent = require(' + request + ');', ' var newContent = require(' + request + ');',
' if(newContent.__esModule) newContent = newContent.default;',
" if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];", " if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];",
' update(newContent);', ' update(newContent);',
' });', ' });',
......
...@@ -36,6 +36,8 @@ module.exports.pitch = function (remainingRequest) { ...@@ -36,6 +36,8 @@ module.exports.pitch = function (remainingRequest) {
'', '',
'// load the styles', '// load the styles',
'var content = require(' + request + ');', 'var content = require(' + request + ');',
// get default export if list is an ES Module (CSS Loader v4+)
"if(content.__esModule) content = content.default;",
// content list format is [id, css, media, sourceMap] // content list format is [id, css, media, sourceMap]
"if(typeof content === 'string') content = [[module.id, content, '']];", "if(typeof content === 'string') content = [[module.id, content, '']];",
'if(content.locals) module.exports = content.locals;' 'if(content.locals) module.exports = content.locals;'
...@@ -66,6 +68,7 @@ module.exports.pitch = function (remainingRequest) { ...@@ -66,6 +68,7 @@ module.exports.pitch = function (remainingRequest) {
' if(!content.locals) {', ' if(!content.locals) {',
' module.hot.accept(' + request + ', function() {', ' module.hot.accept(' + request + ', function() {',
' var newContent = require(' + request + ');', ' var newContent = require(' + request + ');',
' if(newContent.__esModule) newContent = newContent.default;',
" if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];", " if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];",
' update(newContent);', ' update(newContent);',
' });', ' });',
......
...@@ -156,7 +156,7 @@ if (process.env.UNI_USING_V3) { ...@@ -156,7 +156,7 @@ if (process.env.UNI_USING_V3) {
* 转换 upx * 转换 upx
* 转换 px * 转换 px
*/ */
module.exports = postcss.plugin('postcss-uniapp-plugin', function (opts) { const fn = function (opts) {
opts = { opts = {
...defaultOpts, ...defaultOpts,
...opts ...opts
...@@ -265,5 +265,20 @@ if (process.env.UNI_USING_V3) { ...@@ -265,5 +265,20 @@ if (process.env.UNI_USING_V3) {
}) })
} }
} }
}) }
const version = Number(require('postcss/package.json').version.split('.')[0])
if (version < 8) {
module.exports = postcss.plugin('postcss-uniapp-plugin', fn)
} else {
module.exports = function (opts) {
return {
postcssPlugin: 'postcss-uniapp-plugin',
Once: fn(opts)
}
}
module.exports.postcss = true
}
} }
const postcss = require('postcss')
const selectorParser = require('postcss-selector-parser') const selectorParser = require('postcss-selector-parser')
const TAGS = Object.keys(require('@dcloudio/uni-cli-shared').tags) const TAGS = Object.keys(require('@dcloudio/uni-cli-shared').tags)
...@@ -14,34 +13,50 @@ const isInsideKeyframes = function (rule) { ...@@ -14,34 +13,50 @@ const isInsideKeyframes = function (rule) {
let rewriteUrl let rewriteUrl
module.exports = postcss.plugin('postcss-uniapp-plugin', function (opts) { function once (root) {
return function (root, result) { if (!rewriteUrl) {
if (!rewriteUrl) { rewriteUrl = require('@dcloudio/uni-cli-shared/lib/url-loader').rewriteUrl
rewriteUrl = require('@dcloudio/uni-cli-shared/lib/url-loader').rewriteUrl }
} rewriteUrl(root)
rewriteUrl(root)
root.walkRules(rule => {
root.walkRules(rule => { // Transform each rule here
// Transform each rule here if (!isInsideKeyframes(rule)) {
if (!isInsideKeyframes(rule)) { // rule.selectors == comma seperated selectors
// rule.selectors == comma seperated selectors // a, b.c {} => ["a", "b.c"]
// a, b.c {} => ["a", "b.c"] rule.selectors = rule.selectors.map(complexSelector =>
rule.selectors = rule.selectors.map(complexSelector => // complexSelector => simpleSelectors
// complexSelector => simpleSelectors // "a.b#c" => ["a", ".b", "#c"]
// "a.b#c" => ["a", ".b", "#c"] transformSelector(complexSelector, simpleSelectors => {
transformSelector(complexSelector, simpleSelectors => { // only process type selector, leave alone class & id selectors
// only process type selector, leave alone class & id selectors return simpleSelectors.walkTags(tag => {
return simpleSelectors.walkTags(tag => { if (tag.value === 'page') {
if (tag.value === 'page') { tag.value = 'body'
tag.value = 'body' } else if (~TAGS.indexOf(tag.value) && tag.value.substring(
} else if (~TAGS.indexOf(tag.value) && tag.value.substring( 0, 4) !== 'uni-') {
0, 4) !== 'uni-') { tag.value = 'uni-' + tag.value
tag.value = 'uni-' + tag.value }
}
})
}) })
) })
} )
}) }
})
}
const version = Number(require('postcss/package.json').version.split('.')[0])
if (version < 8) {
const postcss = require('postcss')
module.exports = postcss.plugin('postcss-uniapp-plugin', function (opts) {
return once
})
} else {
module.exports = function (opts) {
return {
postcssPlugin: 'postcss-uniapp-plugin',
Once: once
}
} }
})
module.exports.postcss = true
}
...@@ -49,7 +49,7 @@ module.exports = function (source) { ...@@ -49,7 +49,7 @@ module.exports = function (source) {
sourceMap, sourceMap,
rootContext, rootContext,
resourcePath, resourcePath,
resourceQuery resourceQuery = ''
} = loaderContext } = loaderContext
const rawQuery = resourceQuery.slice(1) const rawQuery = resourceQuery.slice(1)
...@@ -79,20 +79,20 @@ module.exports = function (source) { ...@@ -79,20 +79,20 @@ module.exports = function (source) {
const isWin = /^win/.test(process.platform) const isWin = /^win/.test(process.platform)
const normalizePath = path => (isWin ? path.replace(/\\/g, '/') : path) const normalizePath = path => (isWin ? path.replace(/\\/g, '/') : path)
if(!options.compilerOptions){ if (!options.compilerOptions) {
options.compilerOptions = {} options.compilerOptions = {}
} }
options.compilerOptions.autoComponentResourcePath = normalizePath(resourcePath) options.compilerOptions.autoComponentResourcePath = normalizePath(resourcePath)
// fixed by xxxxxx // fixed by xxxxxx
if(!modules && options.compilerOptions && options.compilerOptions.modules){ if (!modules && options.compilerOptions && options.compilerOptions.modules) {
modules = options.compilerOptions.modules modules = options.compilerOptions.modules
} }
const sourcePath = normalizePath(require('@dcloudio/uni-h5/path').src) const sourcePath = normalizePath(require('@dcloudio/uni-h5/path').src)
if (normalizePath(this.resourcePath).indexOf(sourcePath) === 0) { if (normalizePath(this.resourcePath).indexOf(sourcePath) === 0) {
descriptor.styles.length = 0 descriptor.styles.length = 0
options.compilerOptions && (delete options.compilerOptions.modules) options.compilerOptions && (delete options.compilerOptions.modules)
} else if(options.compilerOptions){ } else if (options.compilerOptions) {
options.compilerOptions.modules = modules options.compilerOptions.modules = modules
} }
} }
...@@ -118,7 +118,7 @@ module.exports = function (source) { ...@@ -118,7 +118,7 @@ module.exports = function (source) {
const id = hash( const id = hash(
isProduction isProduction
? (shortFilePath + '\n' + source) ? shortFilePath + '\n' + source.replace(/\r\n/g, '\n')
: shortFilePath : shortFilePath
) )
...@@ -164,7 +164,7 @@ module.exports = function (source) { ...@@ -164,7 +164,7 @@ module.exports = function (source) {
} }
let renderjsImport = `var renderjs` let renderjsImport = `var renderjs`
if((options.isAppView || options.isH5) && descriptor.renderjs){ if ((options.isAppView || options.isH5) && descriptor.renderjs) {
const src = descriptor.renderjs.src || resourcePath const src = descriptor.renderjs.src || resourcePath
const attrsQuery = attrsToQuery(descriptor.renderjs.attrs, 'js') const attrsQuery = attrsToQuery(descriptor.renderjs.attrs, 'js')
const query = `?vue&type=renderjs${attrsQuery}${inheritQuery}` const query = `?vue&type=renderjs${attrsQuery}${inheritQuery}`
...@@ -205,7 +205,7 @@ var component = normalizer( ...@@ -205,7 +205,7 @@ var component = normalizer(
render, render,
staticRenderFns, staticRenderFns,
${hasFunctional ? `true` : `false`}, ${hasFunctional ? `true` : `false`},
${options.isAppNVue ? `null`: (/injectStyles/.test(stylesCode) ? `injectStyles` : `null`)}, ${options.isAppNVue ? `null` : (/injectStyles/.test(stylesCode) ? `injectStyles` : `null`)},
${hasScoped ? JSON.stringify(id) : `null`}, ${hasScoped ? JSON.stringify(id) : `null`},
${isServer ? JSON.stringify(hash(request)) : `null`}, ${isServer ? JSON.stringify(hash(request)) : `null`},
${isShadow ? `true` : `false`}, ${isShadow ? `true` : `false`},
...@@ -228,7 +228,7 @@ var component = normalizer( ...@@ -228,7 +228,7 @@ var component = normalizer(
} }
// fixed by xxxxxx (app-nvue injectStyles) // fixed by xxxxxx (app-nvue injectStyles)
if (options.isAppNVue && /injectStyles/.test(stylesCode)) { if (options.isAppNVue && /injectStyles/.test(stylesCode)) {
code +=`\ninjectStyles.call(component)` code += `\ninjectStyles.call(component)`
} }
// Expose filename. This is used by the devtools and Vue runtime warnings. // Expose filename. This is used by the devtools and Vue runtime warnings.
if (!isProduction) { if (!isProduction) {
...@@ -236,7 +236,7 @@ var component = normalizer( ...@@ -236,7 +236,7 @@ var component = normalizer(
// from the devtools. // from the devtools.
code += `\ncomponent.options.__file = ${JSON.stringify(rawShortFilePath.replace(/\\/g, '/'))}` code += `\ncomponent.options.__file = ${JSON.stringify(rawShortFilePath.replace(/\\/g, '/'))}`
} else if (options.exposeFilename) { } else if (options.exposeFilename) {
// Libraies can opt-in to expose their components' filenames in production builds. // Libraries can opt-in to expose their components' filenames in production builds.
// For security reasons, only expose the file's basename in production. // For security reasons, only expose the file's basename in production.
code += `\ncomponent.options.__file = ${JSON.stringify(filename)}` code += `\ncomponent.options.__file = ${JSON.stringify(filename)}`
} }
...@@ -244,7 +244,6 @@ var component = normalizer( ...@@ -244,7 +244,6 @@ var component = normalizer(
code += `\nrecyclableRender && (component.options["@render"] = recyclableRender)` // fixed by xxxxxx code += `\nrecyclableRender && (component.options["@render"] = recyclableRender)` // fixed by xxxxxx
} }
code += `\nexport default component.exports` code += `\nexport default component.exports`
// console.log(code)
return code return code
} }
......
...@@ -6,28 +6,48 @@ const BasicMatcherRulePlugin = require('webpack/lib/rules/BasicMatcherRulePlugin ...@@ -6,28 +6,48 @@ const BasicMatcherRulePlugin = require('webpack/lib/rules/BasicMatcherRulePlugin
const RuleSetCompiler = require('webpack/lib/rules/RuleSetCompiler') const RuleSetCompiler = require('webpack/lib/rules/RuleSetCompiler')
const UseEffectRulePlugin = require('webpack/lib/rules/UseEffectRulePlugin') const UseEffectRulePlugin = require('webpack/lib/rules/UseEffectRulePlugin')
const objectMatcherRulePlugins = []
try {
const ObjectMatcherRulePlugin = require('webpack/lib/rules/ObjectMatcherRulePlugin')
objectMatcherRulePlugins.push(
new ObjectMatcherRulePlugin('assert', 'assertions'),
new ObjectMatcherRulePlugin('descriptionData')
)
} catch (e) {
const DescriptionDataMatcherRulePlugin = require('webpack/lib/rules/DescriptionDataMatcherRulePlugin')
objectMatcherRulePlugins.push(new DescriptionDataMatcherRulePlugin())
}
const ruleSetCompiler = new RuleSetCompiler([ const ruleSetCompiler = new RuleSetCompiler([
new BasicMatcherRulePlugin('test', 'resource'), new BasicMatcherRulePlugin('test', 'resource'),
new BasicMatcherRulePlugin('mimetype'),
new BasicMatcherRulePlugin('dependency'),
new BasicMatcherRulePlugin('include', 'resource'), new BasicMatcherRulePlugin('include', 'resource'),
new BasicMatcherRulePlugin('exclude', 'resource', true), new BasicMatcherRulePlugin('exclude', 'resource', true),
new BasicMatcherRulePlugin('resource'),
new BasicMatcherRulePlugin('conditions'), new BasicMatcherRulePlugin('conditions'),
new BasicMatcherRulePlugin('resource'),
new BasicMatcherRulePlugin('resourceQuery'), new BasicMatcherRulePlugin('resourceQuery'),
new BasicMatcherRulePlugin('resourceFragment'),
new BasicMatcherRulePlugin('realResource'), new BasicMatcherRulePlugin('realResource'),
new BasicMatcherRulePlugin('issuer'), new BasicMatcherRulePlugin('issuer'),
new BasicMatcherRulePlugin('compiler'), new BasicMatcherRulePlugin('compiler'),
...objectMatcherRulePlugins,
new BasicEffectRulePlugin('type'), new BasicEffectRulePlugin('type'),
new BasicEffectRulePlugin('sideEffects'), new BasicEffectRulePlugin('sideEffects'),
new BasicEffectRulePlugin('parser'), new BasicEffectRulePlugin('parser'),
new BasicEffectRulePlugin('resolve'), new BasicEffectRulePlugin('resolve'),
new BasicEffectRulePlugin('generator'),
new UseEffectRulePlugin() new UseEffectRulePlugin()
]) ])
class VueLoaderPlugin { class VueLoaderPlugin {
apply (compiler) { apply (compiler) {
const normalModule = compiler.webpack
? compiler.webpack.NormalModule
: require('webpack/lib/NormalModule')
// add NS marker so that the loader can detect and report missing plugin // add NS marker so that the loader can detect and report missing plugin
compiler.hooks.compilation.tap(id, compilation => { compiler.hooks.compilation.tap(id, compilation => {
const normalModuleLoader = require('webpack/lib/NormalModule').getCompilationHooks(compilation).loader const normalModuleLoader = normalModule.getCompilationHooks(compilation).loader
normalModuleLoader.tap(id, loaderContext => { normalModuleLoader.tap(id, loaderContext => {
loaderContext[NS] = true loaderContext[NS] = true
}) })
...@@ -38,6 +58,10 @@ class VueLoaderPlugin { ...@@ -38,6 +58,10 @@ class VueLoaderPlugin {
let vueRules = [] let vueRules = []
for (const rawRule of rules) { for (const rawRule of rules) {
// skip rules with 'enforce'. eg. rule for eslint-loader
if (rawRule.enforce) {
continue
}
// skip the `include` check when locating the vue rule // skip the `include` check when locating the vue rule
const clonedRawRule = Object.assign({}, rawRule) const clonedRawRule = Object.assign({}, rawRule)
delete clonedRawRule.include delete clonedRawRule.include
...@@ -71,7 +95,7 @@ class VueLoaderPlugin { ...@@ -71,7 +95,7 @@ class VueLoaderPlugin {
) )
} }
// get the normlized "use" for vue files // get the normalized "use" for vue files
const vueUse = vueRules.filter(rule => rule.type === 'use').map(rule => rule.value) const vueUse = vueRules.filter(rule => rule.type === 'use').map(rule => rule.value)
// get vue-loader options // get vue-loader options
...@@ -110,6 +134,7 @@ class VueLoaderPlugin { ...@@ -110,6 +134,7 @@ class VueLoaderPlugin {
const pitcher = { const pitcher = {
loader: require.resolve('./loaders/pitcher'), loader: require.resolve('./loaders/pitcher'),
resourceQuery: query => { resourceQuery: query => {
if (!query) { return false }
const parsed = qs.parse(query.slice(1)) const parsed = qs.parse(query.slice(1))
return parsed.vue != null return parsed.vue != null
}, },
...@@ -128,8 +153,9 @@ class VueLoaderPlugin { ...@@ -128,8 +153,9 @@ class VueLoaderPlugin {
} }
} }
let uid = 0
function cloneRule (rawRule, refs) { function cloneRule (rawRule, refs) {
const rules = ruleSetCompiler.compileRules('ruleSet', [{ const rules = ruleSetCompiler.compileRules(`clonedRuleSet-${++uid}`, [{
rules: [rawRule] rules: [rawRule]
}], refs) }], refs)
let currentResource let currentResource
...@@ -182,6 +208,10 @@ function cloneRule (rawRule, refs) { ...@@ -182,6 +208,10 @@ function cloneRule (rawRule, refs) {
delete res.test delete res.test
if (rawRule.rules) {
res.rules = rawRule.rules.map(rule => cloneRule(rule, refs))
}
if (rawRule.oneOf) { if (rawRule.oneOf) {
res.oneOf = rawRule.oneOf.map(rule => cloneRule(rule, refs)) res.oneOf = rawRule.oneOf.map(rule => cloneRule(rule, refs))
} }
......
...@@ -5,6 +5,8 @@ module.exports = function ({ ...@@ -5,6 +5,8 @@ module.exports = function ({
visitor: { visitor: {
MemberExpression (path, state) { MemberExpression (path, state) {
if ( if (
// main.js main.ts
state.filename.startsWith(require('path').join(process.env.UNI_INPUT_DIR, 'main.')) &&
t.isIdentifier(path.node.property) && t.isIdentifier(path.node.property) &&
path.node.property.name === '$mount' && path.node.property.name === '$mount' &&
!path.node.$createApp !path.node.$createApp
......
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const webpack = require('webpack')
const { const {
removeExt, removeExt,
normalizePath, normalizePath,
...@@ -121,8 +122,17 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa ...@@ -121,8 +122,17 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa
if (process.env.UNI_PLATFORM === 'mp-alipay') { if (process.env.UNI_PLATFORM === 'mp-alipay') {
beforeCode = ';my.defineComponent || (my.defineComponent = Component);' beforeCode = ';my.defineComponent || (my.defineComponent = Component);'
} }
const source = beforeCode + origSource + const source = beforeCode + origSource + (webpack.version[0] > 4
` ? `
;(${globalVar}["${jsonpFunction}"] = ${globalVar}["${jsonpFunction}"] || []).push([
['${chunkName}'],
{},
function(__webpack_require__){
__webpack_require__('${uniModuleId}')['createComponent'](__webpack_require__(${JSON.stringify(moduleId)}))
}
]);
`
: `
;(${globalVar}["${jsonpFunction}"] = ${globalVar}["${jsonpFunction}"] || []).push([ ;(${globalVar}["${jsonpFunction}"] = ${globalVar}["${jsonpFunction}"] || []).push([
'${chunkName}', '${chunkName}',
{ {
...@@ -133,11 +143,18 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa ...@@ -133,11 +143,18 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa
[['${chunkName}']] [['${chunkName}']]
]); ]);
` `
const newSource = function () { )
return source if (webpack.version[0] > 4) {
const { RawSource } = webpack.sources
const newSource = new RawSource(source)
compilation.updateAsset(name, newSource)
} else {
const newSource = function () {
return source
}
newSource.__$wrappered = true
assets[name].source = newSource
} }
newSource.__$wrappered = true
assets[name].source = newSource
} }
} }
const styleExtname = getPlatformExts().style const styleExtname = getPlatformExts().style
...@@ -186,8 +203,14 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa ...@@ -186,8 +203,14 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa
}) })
delete sourceObj.componentGenerics delete sourceObj.componentGenerics
const source = JSON.stringify(sourceObj, null, 2) const source = JSON.stringify(sourceObj, null, 2)
jsonFile.source = function () { if (webpack.version[0] > 4) {
return source const { RawSource } = webpack.sources
const newSource = new RawSource(source)
compilation.updateAsset(name, newSource)
} else {
jsonFile.source = function () {
return source
}
} }
jsonFile.__$oldSource = oldSource jsonFile.__$oldSource = oldSource
} }
...@@ -205,8 +228,14 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa ...@@ -205,8 +228,14 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa
}).join('') }).join('')
}) })
}) })
templateFile.source = function () { if (webpack.version[0] > 4) {
return templateSource const { RawSource } = webpack.sources
const newSource = new RawSource(templateSource)
compilation.updateAsset(name, newSource)
} else {
templateFile.source = function () {
return templateSource
}
} }
templateFile.__$oldSource = oldSource templateFile.__$oldSource = oldSource
} }
...@@ -215,15 +244,22 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa ...@@ -215,15 +244,22 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa
}) })
} }
// fix mp-qq https://github.com/dcloudio/uni-app/issues/2648 // fix mp-qq https://github.com/dcloudio/uni-app/issues/2648
const appJsonFile = compilation.assets['app.json'] const appJsonName = 'app.json'
const appJsonFile = compilation.assets[appJsonName]
if (process.env.UNI_PLATFORM === 'mp-qq' && appJsonFile) { if (process.env.UNI_PLATFORM === 'mp-qq' && appJsonFile) {
const obj = JSON.parse(appJsonFile.source()) const obj = JSON.parse(appJsonFile.source())
if (obj && obj.usingComponents && !Object.keys(obj.usingComponents).length) { if (obj && obj.usingComponents && !Object.keys(obj.usingComponents).length) {
const componentName = 'fix-2648' const componentName = 'fix-2648'
obj.usingComponents[componentName] = `/${componentName}` obj.usingComponents[componentName] = `/${componentName}`
const source = JSON.stringify(obj, null, 2) const source = JSON.stringify(obj, null, 2)
appJsonFile.source = function () { if (webpack.version[0] > 4) {
return source const { RawSource } = webpack.sources
const newSource = new RawSource(source)
compilation.updateAsset(appJsonName, newSource)
} else {
appJsonFile.source = function () {
return source
}
} }
const files = [ const files = [
{ {
...@@ -258,8 +294,14 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa ...@@ -258,8 +294,14 @@ module.exports = function generateComponent (compilation, jsonpFunction = 'webpa
const componentName = 'plugin-wrapper' const componentName = 'plugin-wrapper'
obj.usingComponents[componentName] = `/${componentName}` obj.usingComponents[componentName] = `/${componentName}`
const source = JSON.stringify(obj, null, 2) const source = JSON.stringify(obj, null, 2)
appJsonFile.source = function () { if (webpack.version[0] > 4) {
return source const { RawSource } = webpack.sources
const newSource = new RawSource(source)
compilation.updateAsset(appJsonName, newSource)
} else {
appJsonFile.source = function () {
return source
}
} }
const files = [ const files = [
{ {
......
const path = require('path') const path = require('path')
const webpack = require('webpack')
const { const {
md5, md5,
...@@ -113,7 +114,7 @@ class WebpackUniMPPlugin { ...@@ -113,7 +114,7 @@ class WebpackUniMPPlugin {
source source
}) => emitFile(file, source, compilation)) }) => emitFile(file, source, compilation))
generateComponent(compilation, compiler.options.output.jsonpFunction) generateComponent(compilation, compiler.options.output[webpack.version[0] > 4 ? 'chunkLoadingGlobal' : 'jsonpFunction'])
resolve() resolve()
}) })
......
...@@ -8,7 +8,8 @@ ...@@ -8,7 +8,8 @@
"es6": false, "es6": false,
"postcss": false, "postcss": false,
"minified": false, "minified": false,
"newFeature": true "newFeature": true,
"bigPackageSizeSupport": true
}, },
"compileType": "miniprogram", "compileType": "miniprogram",
"libVersion": "", "libVersion": "",
......
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const merge = require('merge')
const { const {
parsePages, parsePages,
...@@ -30,6 +31,21 @@ function defaultCopy (name, value, json) { ...@@ -30,6 +31,21 @@ function defaultCopy (name, value, json) {
json[name] = value json[name] = value
} }
function isPlainObject (a) {
if (a === null) {
return false
}
return typeof a === 'object'
}
function deepCopy (name, value, json) {
if (isPlainObject(value) && isPlainObject(json[name])) {
json[name] = merge.recursive(true, json[name], value)
} else {
defaultCopy(name, value, json)
}
}
const pagesJson2AppJson = { const pagesJson2AppJson = {
globalStyle: function (name, value, json) { globalStyle: function (name, value, json) {
json.window = parseStyle(value) json.window = parseStyle(value)
...@@ -115,7 +131,7 @@ const manifestJson2ProjectJson = { ...@@ -115,7 +131,7 @@ const manifestJson2ProjectJson = {
const platformJson2ProjectJson = { const platformJson2ProjectJson = {
appid: defaultCopy, appid: defaultCopy,
setting: defaultCopy, setting: deepCopy,
miniprogramRoot: defaultCopy, miniprogramRoot: defaultCopy,
cloudfunctionRoot: defaultCopy, cloudfunctionRoot: defaultCopy,
qcloudRoot: defaultCopy, qcloudRoot: defaultCopy,
...@@ -123,9 +139,9 @@ const platformJson2ProjectJson = { ...@@ -123,9 +139,9 @@ const platformJson2ProjectJson = {
compileType: defaultCopy, compileType: defaultCopy,
libVersion: defaultCopy, libVersion: defaultCopy,
projectname: defaultCopy, projectname: defaultCopy,
packOptions: defaultCopy, packOptions: deepCopy,
debugOptions: defaultCopy, debugOptions: deepCopy,
scripts: defaultCopy, scripts: deepCopy,
cloudbaseRoot: defaultCopy cloudbaseRoot: defaultCopy
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册